<?php


namespace app\common\model;

use think\Db;
use think\Model;

class BabyGrowLog extends Model{

    /**
     * 获取宝宝数据
     * @param $baby_id
     * @param string $type
     * @return array
     */
    public static function getCanvasBaby($baby_id,$type = 'height'){
        try{
            $baby = Baby::get($baby_id);
            $sex = $baby['sex'] == 1?2:1;
            $result = [];
            $log = BabyGrowLog::getList(['baby_id'=>$baby_id,'order'=>'measure_time asc,id asc']);
            if($log['code'] == 1){
                exception($log['code']);
            }
            $log = $log['data'];

            $cavas_data = [];

            if(empty($log)){
                for($i=0;$i<=18;){
                    $cavas_data[] = '';
                    $i+=0.5;
                }
                return ['cavas_data'=>$cavas_data,'diff'=>0,'start_key'=>-1];
            }

            $max = '';$max_value = '';
            foreach($log as $k =>$v){
                $int_year = floor($v['age']['months']/12);
                $round_year = round($v['age']['months']/12,1);
                if($round_year-$int_year>=0.5){
                    $year = $int_year +0.5;
                }else{
                    $year = $int_year;
                }
                $result["$year"] = $v[$type];
                if(count($log) == $k+1){
                    $max = $year;
                    $max_value = $v[$type];
                }
            }

            if($type == 'height'){
                $s_50 = StandardHeight::where(['age'=>$year,'sex'=>$sex])->column('percent_50');
                $e_50 = StandardHeight::where(['age'=>$year+0.5,'sex'=>$sex])->column('percent_50');
            }else{
                $s_50 = StandardWeight::where(['age'=>$year,'sex'=>$sex])->column('percent_50');
                $e_50 = StandardWeight::where(['age'=>$year+0.5,'sex'=>$sex])->column('percent_50');
            }
            $avg = $s_50[0]+($e_50[0]-$s_50[0])/5*($round_year - $year)*10;
            $diff_height = $max_value - $avg;

            for($i=0;$i<=18;){
                if($max >= $i){
                    if(isset($result["$i"])){
                        $cavas_data["$i"] = $result["$i"];
                    }else{
                        $cavas_data["$i"] = null;
                    }
                }
                $i+=0.5;
            }
            return ['cavas_data'=>$cavas_data,'diff'=>$diff_height,'start_key'=>$max+0.5];
        }catch(\Exception $exception) {
            return ['code' => 1, 'data' => [], 'msg' => $exception->getMessage().$exception->getLine()];
        }
    }


    /**
     * @param $data
     * @return array
     */
    public static function getList($data = []){
        try{
            $con = [];
            $limit = null;
            $offset = 0;

            $order = 'id desc';
            if(!empty($data['order'])){
                $order = $data['order'];
            }
            if(!empty($data['limit'])){
                $limit = $data['limit'];
            }
            if(!empty($data['page'])){
                $offset = $limit*($data['page']-1);
            }

            if(!empty($data['pageNo'])){
                $limit = 10;
                $offset = $limit*($data['pageNo']-1);
            }

            if(!empty($data['parent_id'])){
                $con['a.parent_id'] = $data['parent_id'];
            }
            if(!empty($data['baby_id'])){
                $con['a.baby_id'] = $data['baby_id'];
            }

            if(!empty($data['id'])){
                $con['a.id'] = $data['id'];
            }

            $join = [
                ['baby b', 'a.baby_id = b.id', 'left'],
            ];

            $topic = Db::name('baby_grow_log')->alias('a')->where($con)
                ->order($order)
                ->field('a.*,b.birth,b.sex')
                ->join($join)
                ->limit($offset,$limit)
                ->select();

            foreach ($topic as $k => &$v){
                $v['rate'] = self::rate($v['before_measure_time'],$v['measure_time'],$v['before_height'],$v['height']);
                if($v['birth']){
                    $age_array = self::age($v['birth'],$v['measure_time']);
                    $strand_array = StandardHeight::getStandHeightByMonth($v['sex']==1?2:1,$age_array['months']);
                    if($v['height'] < $strand_array['height_3']){
                        $v['report'] = '身高偏矮';
                    }elseif ($v['height'] > $strand_array['height_97']){
                        $v['report'] = '身高偏高';
                    }else{
                        $v['report'] = '身高处于正常范围';
                    }
                    $v['age'] = self::age($v['birth'],$v['measure_time']);
                }

            }
            $count = Db::name('baby_grow_log')->alias('a')->where($con)->field('a.*,b.birth,b.sex')->join($join)->count();

            return ['code'=>0,'count' => $count,'data'=>$topic,'msg'=>'','pages'=>$limit?ceil($count/$limit):''];
        }catch(\Exception $exception) {
            return ['code' => 1, 'data' => [], 'msg' => $exception->getMessage().$exception->getLine()];
        }
    }


    /**
     * 成长速率
     * @param $s_time
     * @param $e_time
     * @param $s_height
     * @param $e_height
     * @return bool|false|float
     */
    public static function rate($s_time,$e_time,$s_height,$e_height){
        if(!empty($s_time) && !empty($e_time) && !empty($s_height) && !empty($e_height)){
            $diff_height = $e_height-$s_height;
            $diff_days = (strtotime($e_time) - strtotime($s_time))/86400;
            $height = round($diff_height*365/$diff_days,1);
            return  $height>0?$height:false;
        }else{
            return false;
        }
    }

    /**
     * 年纪
     * @param $date1 出生日期
     * @param $date2 测量时间
     * @return array
     */
    public static function age($date1,$date2){
        if(strtotime($date1)>strtotime($date2)){
            $tmp=$date2;
            $date2=$date1;
            $date1=$tmp;
        }
        list($Y1,$m1,$d1)=explode('-',$date1);
        list($Y2,$m2,$d2)=explode('-',$date2);
        $Y=$Y2-$Y1;
        $m=$m2-$m1;
        $d=$d2-$d1;
        if($d<0){
            $d+=(int)date('t',strtotime("-1 month $date2"));
            $m--;
        }
        if($m<0){
            $m+=12;
            $Y--;
        }
        return ['year'=>$Y,'month'=>$m,'day'=>$d,'months'=>$Y*12+$m];
    }
}
